package org.geektimes.configuration.microprofile.better.config.source;

import org.eclipse.microprofile.config.spi.ConfigSource;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @Author: menglinggang
 * @Date: 2021-03-30
 * @Time: 2:49 下午
 */
public abstract class MapBaseConfigSource implements ConfigSource {

    private Map<String, String> propertiesMap = new ConcurrentHashMap<>();

    private String configSourceName;

    private int ordinal;

    public MapBaseConfigSource(String configSourceName, int ordinal) {
        this.configSourceName = configSourceName;
        this.ordinal = ordinal;
        // 获取配置信息
        getProperties();
    }

    @Override
    public final Map<String, String> getProperties() {
        try {
            try {
                prepareConfigData(propertiesMap);
            } catch (Throwable cause) {
                throw new IllegalStateException("准备配置数据发生错误", cause);
            }
        } catch (Exception e) {

        }
        return Collections.unmodifiableMap(propertiesMap);
    }

    protected abstract void prepareConfigData(Map propertiesMap) throws Throwable;


    @Override
    public Set<String> getPropertyNames() {
        return propertiesMap.keySet();
    }

    @Override
    public String getValue(String propertyName) {
        return propertiesMap.get(propertyName);
    }

    @Override
    public String getName() {
        return configSourceName;
    }

    @Override
    public int getOrdinal() {
        return this.ordinal;
    }
}
